package com.cwt_taxi_xa.util;


import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.ResolveInfo;

import com.cwt_taxi_xa.model.AppInfo;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class AppBiz {
	private static final String TAG = "AppBiz.";

	public static final int FILTER_ALL_APP = 0; // 所有应用程序
	public static final int FILTER_SYSTEM_APP = 1; // 系统程序
	public static final int FILTER_THIRD_APP = 2; // 第三方应用程序
	public static final int FILTER_SDCARD_APP = 3; // 安装在SDCard的应用程序

	private Context context;
	private PackageManager pManager;

	public AppBiz(Context context) {
		super();
		this.context = context;
		pManager = context.getPackageManager();
	}

	/**
	 * 检查apk是否安装
	 * @param pkgName
	 * @return
	 */
	public boolean checkInstall(String pkgName) {
		// TODO Auto-generated method stub
		boolean install=false;
		try {
			PackageInfo info = pManager.getPackageInfo(pkgName,1);
			if (info!=null&&info.activities.length>0) {
				install=true;
			}
		} catch (NameNotFoundException e) {
			// TODO Auto-generated catch block
//			e.printStackTrace();
//			AppLog.e(ExceptionUtil.getInfo(e));
		}
		AppLog.i( "包名: "+pkgName+"; 是否安装: " + install);
		return install;
	}



	/**
	 * 启动app
	 * @param pkgName	包名："com.dss.app.carcall"
	 * @param mainClassName		主类名："com.dss.app.carcall.SplashScreen"
	 */
	public void launchApp(String pkgName, String mainClassName){
		try {
			Intent intent = new Intent();
			intent.setClassName(pkgName, mainClassName);
			context.startActivity(intent);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			AppLog.e(ExceptionUtil.getInfo(e));
		}
	}

	/**
	 * 启动app
	 * @param pkgName	包名："com.dss.app.carcall"
	 */
	public void launchApp(String pkgName){
		AppLog.i( "==============4================"+pkgName);
		try {
			AppLog.i( "pkgName: "+pkgName);
			if(!checkInstall(pkgName)){
				AppLog.e("应用程序未安装！");
				return;
			}

			Intent intent = new Intent();
			intent = context.getPackageManager().getLaunchIntentForPackage(pkgName);
			intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT
					| Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
			context.startActivity(intent);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			AppLog.e(ExceptionUtil.getInfo(e));
		}
	}

	/*	*//**
	 * 启动app
	 * @param pkgName	包名："com.dss.app.carcall"
	 *//*
	public void launchApp(String pkgName){
		AppLog.i( "==============4================"+pkgName);
		try {
			AppLog.i( "pkgName: "+pkgName);
			if(!checkInstall(pkgName)){
				NetworkHandler.showToastForCustom("应用程序未安装！");
				return;
			}

			Intent intent = new Intent();
			intent = context.getPackageManager().getLaunchIntentForPackage(pkgName);
			intent.setAction(Intent.ACTION_MAIN);
			intent.addCategory(Intent.CATEGORY_LAUNCHER);
			intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT
					| Intent.FLAG_ACTIVITY_NEW_TASK
					| Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
			context.startActivity(intent);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			AppLog.e(ExceptionUtil.getInfo(e));
		}
	}*/

	/**
	 * 通过 包名获取主类名
	 * @param packageName 包名
	 * @return 主类名
	 */
	public String getMainClassName(String packageName) {
		String className = "";
		try {
			PackageInfo packageInfo = pManager.getPackageInfo(packageName, 0);
			Intent resolveIntent = new Intent(Intent.ACTION_MAIN, null);
			resolveIntent.addCategory(Intent.CATEGORY_LAUNCHER);
			resolveIntent.setPackage(packageInfo.packageName);

			List<ResolveInfo> apps = pManager.queryIntentActivities(resolveIntent, 0);

			ResolveInfo ri = apps.iterator().next();
			if (ri != null ) {
				className = ri.activityInfo.name;
			}
			return className;
		} catch (NameNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			AppLog.e(ExceptionUtil.getInfo(e));
			return className;
		}
	}

	/**
	 *	根据查询条件，查询特定的ApplicationInfo
	 *	@param filter
	 *	FILTER_ALL_APP = 0; 所有应用程序
	 *	FILTER_SYSTEM_APP = 1;  系统程序
	 *	FILTER_THIRD_APP = 2; 第三方应用程序
	 *	FILTER_SDCARD_APP = 3;  安装在SDCard的应用程序
	 * 	@return
	 */
	public List<AppInfo> queryFilterAppInfo(int filter) {
		// 查询所有已经安装的应用程序
		List<ApplicationInfo> listAppcations = pManager
				.getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES);
		Collections.sort(listAppcations,
				new ApplicationInfo.DisplayNameComparator(pManager));// 排序
		List<AppInfo> appInfos = new ArrayList<AppInfo>(); // 保存过滤查到的AppInfo
		// 根据条件来过滤
		switch (filter) {
			case FILTER_ALL_APP: // 所有应用程序
				appInfos.clear();
				for (ApplicationInfo app : listAppcations) {
					appInfos.add(getAppInfo(app));
				}
				return appInfos;
			case FILTER_SYSTEM_APP: // 系统程序
				appInfos.clear();
				for (ApplicationInfo app : listAppcations) {
					if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
						appInfos.add(getAppInfo(app));
					}
				}
				return appInfos;
			case FILTER_THIRD_APP: // 第三方应用程序
				appInfos.clear();
				for (ApplicationInfo app : listAppcations) {
					//非系统程序
					if ((app.flags & ApplicationInfo.FLAG_SYSTEM) <= 0) {
						appInfos.add(getAppInfo(app));
					}
					//本来是系统程序，被用户手动更新后，该系统程序也成为第三方应用程序了
					else if ((app.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0){
						appInfos.add(getAppInfo(app));
					}
				}
				break;
			case FILTER_SDCARD_APP: // 安装在SDCard的应用程序
				appInfos.clear();
				for (ApplicationInfo app : listAppcations) {
					if ((app.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
						appInfos.add(getAppInfo(app));
					}
				}
				return appInfos;
			default:
				return null;
		}
		return appInfos;
	}

	// 构造一个AppInfo对象 ，并赋值
	private AppInfo getAppInfo(ApplicationInfo app) {
		AppInfo appInfo = new AppInfo();
		appInfo.setAppLabel((String) app.loadLabel(pManager));
		appInfo.setAppIcon(app.loadIcon(pManager));
		appInfo.setPkgName(app.packageName);
		return appInfo;
	}

//	/**
//	 *	根据查询条件，查询特定的ApplicationInfo
//	 *	@param filter
//	 *	FILTER_ALL_APP = 0; 所有应用程序
//	 *	FILTER_SYSTEM_APP = 1;  系统程序
//	 *	FILTER_THIRD_APP = 2; 第三方应用程序
//	 *	FILTER_SDCARD_APP = 3;  安装在SDCard的应用程序
//	 * 	@return
//	 */
//	public List<AppInfo> queryFilterAppInfo(int filter) {
//		// 查询所有已经安装的应用程序
//		List<ApplicationInfo> listAppcations = pManager
//				.getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES);
//		Collections.sort(listAppcations,
//				new ApplicationInfo.DisplayNameComparator(pManager));// 排序
//		List<AppInfo> appInfos = new ArrayList<AppInfo>(); // 保存过滤查到的AppInfo
//		// 根据条件来过滤
//		switch (filter) {
//		case FILTER_ALL_APP: // 所有应用程序
//			appInfos.clear();
//			for (ApplicationInfo app : listAppcations) {
//				appInfos.add(getAppInfo(app));
//			}
//			return appInfos;
//		case FILTER_SYSTEM_APP: // 系统程序
//			appInfos.clear();
//			for (ApplicationInfo app : listAppcations) {
//				if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
//					appInfos.add(getAppInfo(app));
//				}
//			}
//			return appInfos;
//		case FILTER_THIRD_APP: // 第三方应用程序
//			appInfos.clear();
//			for (ApplicationInfo app : listAppcations) {
//				//非系统程序
//				if ((app.flags & ApplicationInfo.FLAG_SYSTEM) <= 0) {
//					appInfos.add(getAppInfo(app));
//				}
//				//本来是系统程序，被用户手动更新后，该系统程序也成为第三方应用程序了
//				else if ((app.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0){
//					appInfos.add(getAppInfo(app));
//				}
//			}
//			break;
//		case FILTER_SDCARD_APP: // 安装在SDCard的应用程序
//			appInfos.clear();
//			for (ApplicationInfo app : listAppcations) {
//				if ((app.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
//					appInfos.add(getAppInfo(app));
//				}
//			}
//			return appInfos;
//		default:
//			return null;
//		}
//		return appInfos;
//	}
//	// 构造一个AppInfo对象 ，并赋值
//	private AppInfo getAppInfo(ApplicationInfo app) {
//		AppInfo appInfo = new AppInfo();
//		appInfo.setAppLabel((String) app.loadLabel(pManager));
//		appInfo.setAppIcon(app.loadIcon(pManager));
//		appInfo.setPkgName(app.packageName);
//		return appInfo;
//	}

	/**
	 * 获取应用
	 * @return
	 */
//	public List<AppInfo> queryAppInfo() {
//		List<AppInfo> appInfos = new ArrayList<AppInfo>();
//		Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
//		mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
//		// 通过查询，获得所有ResolveInfo对象.
//		//List<ResolveInfo> resolveInfos = pm.queryIntentActivities(mainIntent, 0);
//		List<ResolveInfo> resolveInfos = pManager.queryIntentActivities(mainIntent,PackageManager.GET_UNINSTALLED_PACKAGES);
//		// 调用系统排序 ， 根据name排序
//		// 该排序很重要，否则只能显示系统应用，而不能列出第三方应用程序
//		Collections.sort(resolveInfos,new ResolveInfo.DisplayNameComparator(pManager));
//		for (ResolveInfo reInfo : resolveInfos) {
//			String activityName = reInfo.activityInfo.name; // 获得该应用程序的启动Activity的name
//			String pkgName = reInfo.activityInfo.packageName; // 获得应用程序的包名
//			String appLabel = (String) reInfo.loadLabel(pManager); // 获得应用程序的Label
//			Drawable icon = reInfo.loadIcon(pManager); // 获得应用程序图标
//			// 为应用程序的启动Activity 准备Intent
//			Intent launchIntent = new Intent();
//			launchIntent.setComponent(new ComponentName(pkgName,
//					activityName));
//			int count = 0;
//			String[] filterPkgNames = Constants.filterPkgNamesForRelease;
//			for(String filter:filterPkgNames){
//				if(pkgName.equals(filter)){
//					count ++;
//				}
//			}
//			if(count == 0){
//				// 创建一个AppInfo对象，并赋值
//				AppInfo appInfo = new AppInfo();
//				appInfo.setAppLabel(appLabel);
//				appInfo.setPkgName(pkgName);
//				appInfo.setAppIcon(icon);
//				appInfo.setIntent(launchIntent);
//				appInfos.add(appInfo); // 添加至列表中
//				//System.out.println(appLabel + " activityName---" + activityName + " pkgName---" + pkgName); 
//			}
//		}  
//		return appInfos;
//	}
}
